<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库单号" prop="receiptOrderNo">
        <el-input
          v-model="queryParams.receiptOrderNo"
          placeholder="请输入入库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库类型" prop="receiptOrderType">
        <el-select v-model="queryParams.receiptOrderType" placeholder="请选择入库类型" clearable>
          <el-option
            v-for="dict in dict.type.wms_receipt_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" clearable>
          <el-option
            v-for="supplier in supplierPullData"
            :key="supplier.id"
            :label="supplier.supplierName"
            :value="supplier.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库状态" prop="receiptOrderStatus">
        <el-select v-model="queryParams.receiptOrderStatus" placeholder="请选择入库状态" clearable>
          <el-option
            v-for="dict in dict.type.wms_receipt_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:receiptOrder:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['wms:receiptOrder:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['wms:receiptOrder:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['wms:receiptOrder:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="receiptOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="唯一值" align="center" prop="id" />-->
      <el-table-column label="序号" type="index" width="50" align="center" >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="入库单号" align="center" prop="receiptOrderNo" />
      <el-table-column label="入库类型" align="center" prop="receiptOrderType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_receipt_type" :value="scope.row.receiptOrderType"/>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="supplierId">
        <template slot-scope="scope">
          <supplier-tag :options="supplierPullData" :value="scope.row.supplierId"/>
        </template>
      </el-table-column>
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="入库状态" align="center" prop="receiptOrderStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_receipt_status" :value="scope.row.receiptOrderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:receiptOrder:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:receiptOrder:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入库单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-input v-model="form.id" type="hidden" />
        <el-form-item label="入库单号" prop="receiptOrderNo">
          <el-input v-model="form.receiptOrderNo" readonly="readonly" />
        </el-form-item>
        <el-form-item label="入库类型" prop="receiptOrderType">
          <el-select v-model="form.receiptOrderType" :disabled="form.id" placeholder="请选择入库类型">
            <el-option
              v-for="dict in dict.type.wms_receipt_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="form.supplierId" :disabled="form.id" placeholder="请选择供应商">
            <el-option
              v-for="supplier in supplierPullData"
              :key="supplier.id"
              :label="supplier.supplierName"
              :value="supplier.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" :disabled="form.id" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="入库状态" prop="receiptOrderStatus">
          <el-select v-model="form.receiptOrderStatus" :disabled="form.id" placeholder="请选择入库状态">
            <el-option
              v-for="dict in dict.type.wms_receipt_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" :disabled="form.id" placeholder="请输入备注" />
        </el-form-item>
        <el-divider content-position="center">入库单详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button :disabled="form.id" type="primary" icon="el-icon-plus" size="mini" @click="handleAddWmsReceiptOrderDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button :disabled="form.id" type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWmsReceiptOrderDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="wmsReceiptOrderDetailList"   :row-class-name="rowWmsReceiptOrderDetailIndex" @selection-change="handleWmsReceiptOrderDetailSelectionChange" ref="wmsReceiptOrderDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="物料" prop="itemId" width="150">
            <template slot-scope="scope">
              <el-select :disabled="form.id" v-model="scope.row.itemId" placeholder="请选择物料">
                <el-option
                  v-for="item in itemPullData"
                  :key="item.id"
                  :label="item.itemName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="计划数量" prop="planQuantity" width="150">
            <template slot-scope="scope">
              <el-input-number :disabled="form.id" v-model="scope.row.planQuantity"  :min="0" placeholder="请输入计划数量" :precision='2'/>
            </template>
          </el-table-column>
          <el-table-column label="实际数量" prop="realQuantity" width="150">
            <template slot-scope="scope">
              <el-input-number :disabled="form.id" v-model="scope.row.realQuantity"  :min="0" placeholder="请输入实际数量" :precision='2'/>
            </template>
          </el-table-column>
          <el-table-column label="所属仓库" prop="warehouseId" width="150">
            <template slot-scope="scope">
              <el-select :disabled="form.id" v-model="scope.row.warehouseId" placeholder="请选择所属仓库" @change="handleWarehouseChange(scope.row)">
                <el-option
                  v-for="warehouse in warehousePullData"
                  :key="warehouse.id"
                  :label="warehouse.warehouseName"
                  :value="warehouse.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="所属库区" prop="areaId" width="150">
            <template slot-scope="scope">
              <el-select :disabled="form.id" v-model="scope.row.areaId" placeholder="请选择所属库区" @change="handleAreaChange(scope.row)">
                <el-option
                  v-for="area in scope.row.filteredAreaData"
                  :key="area.id"
                  :label="area.areaName"
                  :value="area.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="货架" prop="rackId" width="150">
            <template slot-scope="scope">
              <el-select :disabled="form.id" v-model="scope.row.rackId" placeholder="请选择所属货架">
                <el-option
                  v-for="rack in scope.row.filteredRackData"
                  :key="rack.id"
                  :label="rack.rackName"
                  :value="rack.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>


          <el-table-column label="入库状态" prop="receiptOrderStatus" width="150">
            <template slot-scope="scope">
              <el-select :disabled="form.id" v-model="scope.row.receiptOrderStatus" placeholder="请选择入库状态">
                <el-option
                  v-for="dict in dict.type.wms_receipt_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150">
            <template slot-scope="scope">
              <el-input :disabled="form.id" v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="form.id" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listReceiptOrder,
    getReceiptOrder,
    delReceiptOrder,
    addReceiptOrder,
    updateReceiptOrder,
    genReceiptOrderNo
  } from "@/api/wms/receiptOrder";
  import {pullWarehouse} from "@/api/wms/warehouse";
  import {pullArea} from "@/api/wms/area";
  import {pullRack} from "@/api/wms/rack";
  import {pullSupplier} from "@/api/wms/supplier";
  import {pullItem} from "@/api/wms/item";

  export default {
    name: "ReceiptOrder",
    dicts: ['wms_receipt_status', 'sys_user_sex', 'wms_receipt_type'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 子表选中数据
        checkedWmsReceiptOrderDetail: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 入库单表格数据
        receiptOrderList: [],
        // 入库单详情表格数据
        wmsReceiptOrderDetailList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          receiptOrderNo: null,
          receiptOrderType: null,
          supplierId: null,
          orderNo: null,
          receiptOrderStatus: null,
        },
        supplierPullData: [],
        warehousePullData: [],
        areaPullData: [],
        rackPullData: [],
        itemPullData: [],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          orderNo:[
            { required: true, message: "订单号不能为空", trigger: "blur" }
          ],
          receiptOrderNo: [
            { required: true, message: "入库单号不能为空", trigger: "blur" }
          ],
          receiptOrderType: [
            { required: true, message: "入库类型不能为空", trigger: "change" }
          ],
          supplierId: [
            { required: true, message: "供应商不能为空", trigger: "change" }
          ],
          receiptOrderStatus: [
            { required: true, message: "入库状态不能为空", trigger: "change" }
          ],
          // 针对明细中的各个字段进行验证
          wmsReceiptOrderDetailList: [
            {
              type: 'array',
              required: true,
              message: '请添加至少一条入库单详情信息',
              trigger: 'change'
            },
            {
              validator: this.validateDetailList,
              trigger: 'change'
            }]
        }
      };
    },
    created() {
      this.getList();

      /** 查询供应商下拉数据 **/
      pullSupplier().then(response => {
        this.supplierPullData = response.data;
      });

      /** 查询仓库下拉数据 **/
      pullWarehouse().then(response => {
        this.warehousePullData = response.data;
      });

      /** 查询库区下拉数据 **/
      pullArea().then(response => {
        this.areaPullData = response.data;
      });

      /** 查询库区下拉数据 **/
      pullRack().then(response => {
        this.rackPullData = response.data;
      });

      /** 查询物料下拉数据 **/
      pullItem().then(response => {
        this.itemPullData = response.data;
      });

    },
    methods: {
      handleWarehouseChange(row) {
        // 当仓库变化时，重置库区和货架，并过滤出该仓库的库区
        row.areaId = null;
        row.rackId = null;
        row.filteredAreaData = this.areaPullData.filter(area => area.warehouseId === row.warehouseId);
        row.filteredRackData = []; // 清空货架数据
      },
      handleAreaChange(row) {
        // 当库区变化时，重置货架，并过滤出该库区的货架
        row.rackId = null;
        row.filteredRackData = this.rackPullData.filter(rack => rack.areaId === row.areaId);
      },
      /** 查询入库单列表 */
      getList() {
        this.loading = true;
        listReceiptOrder(this.queryParams).then(response => {
          this.receiptOrderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          receiptOrderNo: null,
          receiptOrderType: null,
          supplierId: null,
          orderNo: null,
          receiptOrderStatus: null,
          remark: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.wmsReceiptOrderDetailList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        /** 生成新的订单号 **/
        genReceiptOrderNo().then(response => {
          this.form.receiptOrderNo = response.msg;
        })
        this.open = true;
        this.title = "添加入库单";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getReceiptOrder(id).then(response => {
          this.form = response.data;
          this.wmsReceiptOrderDetailList = response.data.wmsReceiptOrderDetailList;
          this.open = true;
          this.title = "修改入库单";
        });
      },
      /** 提交按钮 */
      submitForm() {

        this.validateDetailList({}, this.wmsReceiptOrderDetailList, (error) => {
          if (error) {
            // 如果有错误，提示用户
            this.$message.error(error.message);
          } else {
            this.$refs["form"].validate(valid => {
              if (valid) {
                this.form.wmsReceiptOrderDetailList = this.wmsReceiptOrderDetailList;
                if (this.form.id != null) {
                  updateReceiptOrder(this.form).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  });
                } else {
                  addReceiptOrder(this.form).then(response => {
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  });
                }
              }
            });
          }
        });



      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除入库单编号为"' + ids + '"的数据项？').then(function() {
          return delReceiptOrder(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 入库单详情序号 */
      rowWmsReceiptOrderDetailIndex({ row, rowIndex }) {
        row.index = rowIndex + 1;
      },
      /** 入库单详情添加按钮操作 */
      handleAddWmsReceiptOrderDetail() {
        let obj = {};
        obj.itemId = "";
        obj.planQuantity = "";
        obj.realQuantity = "";
        obj.rackId = "";
        obj.remark = "";
        obj.warehouseId = "";
        obj.areaId = "";
        obj.receiptOrderStatus = "";
        this.wmsReceiptOrderDetailList.push(obj);
      },
      /** 入库单详情删除按钮操作 */
      handleDeleteWmsReceiptOrderDetail() {
        if (this.checkedWmsReceiptOrderDetail.length == 0) {
          this.$modal.msgError("请先选择要删除的入库单详情数据");
        } else {
          const wmsReceiptOrderDetailList = this.wmsReceiptOrderDetailList;
          const checkedWmsReceiptOrderDetail = this.checkedWmsReceiptOrderDetail;
          this.wmsReceiptOrderDetailList = wmsReceiptOrderDetailList.filter(function(item) {
            return checkedWmsReceiptOrderDetail.indexOf(item.index) == -1
          });
        }
      },
      // 自定义验证函数，验证每个明细的字段
      validateDetailList(rule, value, callback) {
        if (!value || value.length === 0) {
          return callback(new Error('请至少添加一条明细'));
        }

        // 遍历明细列表，逐一检查每个字段
        for (let i = 0; i < value.length; i++) {
          let detail = value[i];
          if (!detail.itemId) {
            return callback(new Error('第 ' + (i + 1) + ' 行的物料不能为空'));
          }
          if (!detail.planQuantity) {
            return callback(new Error('第 ' + (i + 1) + ' 行的计划数量不能为空'));
          }
          if (!detail.realQuantity) {
            return callback(new Error('第 ' + (i + 1) + ' 行的实际数量不能为空'));
          }
          if (!detail.rackId) {
            return callback(new Error('第 ' + (i + 1) + ' 行的所属货架不能为空'));
          }
          if (!detail.warehouseId) {
            return callback(new Error('第 ' + (i + 1) + ' 行的所属仓库不能为空'));
          }
          if (!detail.areaId) {
            return callback(new Error('第 ' + (i + 1) + ' 行的所属库区不能为空'));
          }
        }
        // 验证通过
        callback();
      },
      /** 复选框选中数据 */
      handleWmsReceiptOrderDetailSelectionChange(selection) {
        this.checkedWmsReceiptOrderDetail = selection.map(item => item.index)
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('wms/receiptOrder/export', {
          ...this.queryParams
        }, `receiptOrder_${new Date().getTime()}.xlsx`)
      },

    }
  };
</script>
